'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';

interface User {
  id: string;
  username: string;
  isAdmin: boolean;
}

export default function Navbar() {
  const router = useRouter();
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    fetchUser();
  }, []);

  const fetchUser = async () => {
    try {
      const res = await fetch('/api/auth/me');
      const data = await res.json();
      if (data.success) {
        setUser(data.user);
      } else {
        router.push('/');
      }
    } catch (error) {
      router.push('/');
    }
  };

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout', { method: 'POST' });
      router.push('/');
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <nav className="bg-card/80 backdrop-blur-xl border-b border-border/50 shadow-sm sticky top-0 z-50">
      <div className="container flex justify-between items-center py-4">
        <h1 className="text-2xl font-semibold text-primary tracking-tight">
          单词乐园
        </h1>
        <div className="flex items-center gap-3">
          {user && (
            <>
              <span className="text-muted-foreground text-sm">欢迎, {user.username}</span>
              {user.isAdmin && (
                <button
                  className="px-4 py-2 text-sm rounded-xl bg-secondary text-secondary-foreground hover:bg-secondary/80 transition-all duration-300 shadow-sm hover:shadow-md active:scale-[0.98]"
                  onClick={() => window.open('/admin', '_blank')}
                >
                  管理端
                </button>
              )}
              <button
                className="px-4 py-2 text-sm rounded-xl bg-secondary text-secondary-foreground hover:bg-secondary/80 transition-all duration-300 shadow-sm hover:shadow-md active:scale-[0.98]"
                onClick={handleLogout}
              >
                退出
              </button>
            </>
          )}
        </div>
      </div>
    </nav>
  );
}

